'use client'
import React, {PropsWithChildren, useEffect, useMemo, useState,} from "react"
import {Button, Layout, Menu, notification, theme} from "antd";
import {
    NotificationOutlined,
    UserOutlined,
    LogoutOutlined,
    ShoppingCartOutlined,
    BankOutlined,
    BarcodeOutlined,
    TeamOutlined,
    InboxOutlined,
    SolutionOutlined, SettingOutlined
} from "@ant-design/icons";
import {LaptopOutlined} from "@ant-design/icons-svg";
import {observer} from "mobx-react-lite";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import {getMe} from "../../apis/EmployeeApi";
import {Authority} from "../../apis/RoleApi";

import {systemServiceStore} from "../../store/SystemServiceStore";
import {getUnconsumedNotifications} from "../../apis/NotificationApi";
import {getMarketOrderDetailWithoutItems} from "../../apis/MarketOrderApi";
import UpdatePasswordModal from "../../components/UpdatePasswordModal";
import {logOut} from "../../apis/AuthorizationApi";
import {useLocation, useNavigate} from "react-router-dom";
import RequireAuthorization from "../../components/RequireAuthorization";
import {MenuItemType} from "antd/es/menu/interface";
import EditEmployeeSettingFormDrawer from "../../components/EditEmployeeSettingFormDrawer";
import FullScreenWatermark from "../../components/FullScreenWatermark";

const DashboardLayout: React.FC<PropsWithChildren & {
    [key: string]: React.ReactNode
}> = ({children}) => {
    useEffect(() => {
        if (employeeAuthorizationStore.authorization) {
            getMe().then(response => employeeAuthorizationStore.setEmployee(response.data))
            systemServiceStore.initFromClient()
        }
    }, [employeeAuthorizationStore.authorization]);

    const [api, contextHolder] = notification.useNotification();
    let navigate = useNavigate();

    useEffect(() => {
        let timer: NodeJS.Timeout | null = null;
        if (employeeAuthorizationStore.hasLogIn) {
            let callback = async () => {
                let response = await getUnconsumedNotifications();
                let notifications = response.data;
                for (const notification of notifications) {
                    switch (notification.type) {
                        case "SUBMITTED_MARKET_ORDER":
                            let marketDetail = (await getMarketOrderDetailWithoutItems(notification.data.id)).data;
                            api.info({
                                message: "新的订单",
                                description: `来自${marketDetail.market.name}`,
                                duration: null,
                                onClick: () => {
                                    navigate(`/markets/orders/${notification.data.id}`)
                                }
                            })
                            break;
                        case "CONFIRMED_MARKET_ORDER":
                            break;
                    }
                }
            };
            callback();
            timer = setInterval(callback, 1000 * 60)
        }
        return () => {
            timer && clearTimeout(timer)
        }
    }, [employeeAuthorizationStore.hasLogIn, api]);

    [UserOutlined, LaptopOutlined, NotificationOutlined].map(
        (icon, index) => {
            const key = String(index + 1);

            return {
                key: `sub${key}`,
                icon: icon,
                label: `subnav ${key}`,

                children: new Array(4).fill(null).map((_, j) => {
                    const subKey = index * 4 + j + 1;
                    return {
                        key: subKey,
                        label: `option${subKey}`,
                    };
                }),
            };
        },
    );

    const pathname = useLocation().pathname;
    const leftSideMenuItems: Array<MenuItemType & {
        authorities: Array<Authority>,
        children?: Array<MenuItemType & {
            authorities: Array<Authority>
        }>
    }> = [
        {
            icon: <TeamOutlined/>,
            key: "/employees",
            label: "人员",
            authorities: ["人员_查询" as Authority],
            children: [
                {
                    key: "/employees",
                    label: "人员",
                    authorities: ["人员_查询"]
                },
                {
                    key: "/roles",
                    label: "权限",
                    authorities: ["人员_角色_查询"]
                },
                {
                    key: "/employees/operateRecords",
                    label: "操作记录",
                    authorities: ["人员_操作记录_查询"]
                }
            ]
        },
        {
            icon: <BarcodeOutlined/>,
            key: "/goods",
            label: "货品",
            authorities: ["货品_查询" as Authority],
            children: [
                {
                    key: "/goods",
                    label: "货品",
                    authorities: ["货品_查询"],
                },
                {
                    key: "/goods/categories",
                    label: "分类",
                    authorities: ["货品_分类_查询"]
                },
                {
                    key: "/goods/brands",
                    label: "品牌",
                    authorities: ["货品_品牌_查询"]
                },
                {
                    key: "/goods/brands/groups",
                    label: "品牌组",
                    authorities: ["货品_品牌分组_查询"]
                },
                {
                    key: "/goods/factories",
                    label: "厂商",
                    authorities: ["货品_厂商_查询"]
                },
                {
                    key: "/goodsScratches",
                    label: "草稿单",
                    authorities: ["货品_草稿单"],
                },
            ]
        },
        {
            icon: <BankOutlined/>,
            key: "/markets",
            label: "卖场",
            authorities: ["卖场_查询" as Authority],
            children: [
                {
                    key: "/markets",
                    label: "卖场",
                    authorities: ["卖场_查询" as Authority],
                },
                {
                    key: "/markets/orders",
                    label: "订单",
                    authorities: ["卖场_订单_查询" as Authority],
                },
                {
                    key: "/markets/deliveryOrders",
                    label: "送货单",
                    authorities: ["卖场_送货单_查询"]
                },
                {
                    key: "/markets/returnOrders",
                    label: "退货单",
                    authorities: ["卖场_退货单_查询"]
                },
                {
                    key: "/markets/saleDocuments",
                    label: "销售单",
                    authorities: ["卖场_销售单_查询"]
                },
                {
                    key: "/markets/checkInventoryRecords",
                    label: "盘点",
                    authorities: ["卖场_送货单_查询"]
                },
            ]
        },
        {
            icon: <InboxOutlined/>,
            key: "/checkInventoryRecords",
            label: "库存",
            authorities: ["库存_盘点_查询"],
            children: [
                {
                    key: "/checkInventoryRecords",
                    label: "盘点",
                    authorities: ["库存_盘点_查询"]
                },
            ]
        },
        {
            icon: <SolutionOutlined/>,
            key: "/directSales",
            label: "经销",
            authorities: ["经销_客户_查询"],
            children: [
                {
                    key: "/directSales/orders",
                    label: "经销",
                    authorities: ["经销_查询"]
                },
                {
                    key: "/directSales/clients",
                    label: "客户",
                    authorities: ["经销_客户_查询"]
                },
            ]
        },
        {
            icon: <ShoppingCartOutlined/>,
            key: "/procurements",
            label: "采购",
            authorities: ["采购_查询"],
            children: [
                {
                    key: "/procurements",
                    label: "采购",
                    authorities: ["采购_查询"],
                },
                {
                    key: "/procurements/receipts",
                    label: "入库",
                    authorities: ["采购_入库_查询"],
                },
                {
                    key: "/procurements/suppliers",
                    label: "供货商",
                    authorities: ["采购_供货商_查询"],
                },
                {
                    key: "/procurementReturns",
                    label: "退货",
                    authorities: ["采购_退货_查询"],
                },
            ],
        },
    ];

    let token = theme.useToken();

    const availableMenuItems = useMemo(() => {
        return leftSideMenuItems.filter(item => employeeAuthorizationStore.hasAllAuthority(...item.authorities)).map(
            item => ({
                ...item,
                children: item.children?.filter(child => employeeAuthorizationStore.hasAllAuthority(...child.authorities)),
            })
        )
    }, [employeeAuthorizationStore.employee?.authorities, leftSideMenuItems])
    const [openUpdatePasswordModal, setOpenUpdatePasswordModal] = useState(false)

    const [openSettingDrawer, setOpenSettingDrawer] = useState(false)
    return (
        <>
            <>{contextHolder}</>
            <UpdatePasswordModal open={openUpdatePasswordModal} onCancel={() => {
                setOpenUpdatePasswordModal(false)
            }}/>
            <Layout style={{height: "100vh"}}>
                <Layout.Header style={{display: 'flex', alignItems: 'center'}}>
                    <h3 style={{color: token.token.colorWhite}}>{systemServiceStore.systemService?.name}</h3>
                    <div style={{flexGrow: 1}}></div>
                    <Button type={"link"}
                            onClick={() => setOpenUpdatePasswordModal(true)}>修改密码</Button>
                    <Button type={"link"}
                            onClick={async () => {
                                await logOut()
                                return employeeAuthorizationStore.logOut();
                            }}><LogoutOutlined/>退出</Button>
                    <Button type={"link"} onClick={() => {
                        setOpenSettingDrawer(true)
                    }}>
                        <SettingOutlined/>设置
                    </Button>
                    <div style={{color: token.token.colorWhite}}>
                        <UserOutlined/>{employeeAuthorizationStore.employee?.name}
                    </div>
                </Layout.Header>
                <Layout>
                    <Layout.Sider width={200} style={{overflowY: "auto"}}>
                        <Menu
                            defaultOpenKeys={availableMenuItems.filter(it => pathname.startsWith(it.key as string)).map(it => it.key as string)}
                            mode={"inline"}
                            selectedKeys={availableMenuItems.flatMap(it => [it, ...(it.children ?? [])]).map(it => it.key as string).filter(it => {
                                return pathname == it
                            })}
                            style={{borderRight: 0, minHeight: "100%"}}
                            items={availableMenuItems}
                            onSelect={item => {
                                navigate(item.key);
                            }}
                        />
                    </Layout.Sider>
                    <Layout.Content
                        style={{
                            margin: 0,
                            overflowY: "hidden",
                        }}
                    >
                        <RequireAuthorization>
                            {children}
                        </RequireAuthorization>
                    </Layout.Content>
                </Layout>
            </Layout>

            <EditEmployeeSettingFormDrawer onClose={() => {
                setOpenSettingDrawer(false)
            }} open={openSettingDrawer}/>

            {employeeAuthorizationStore.employee?.name?<FullScreenWatermark text={`${employeeAuthorizationStore.employee?.name}|${employeeAuthorizationStore.employee.id}`}/>:undefined}
        </>
    )
}

export default observer(DashboardLayout)